package ciprian.google.parser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;

import org.xmlpull.v1.XmlSerializer;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.util.Xml;

import ciprian.google.Constants;
import ciprian.google.location_mgr.MapPoint;
import ciprian.google.utils.Prefs;

public class PointsToGPX {
    /**
     * 
     * @return the route file path
     */
    public static String getTheRouteFilePath() {
        SharedPreferences settings = Prefs.get();
        String routeFilePath = settings.getString(Constants.SELECTED_ROUTE_FILE, null);

        if (routeFilePath == null) {
            // if the route file wasn't selected
            routeFilePath = generateNewFilePath();
        }

        File file = new File(routeFilePath);
        if (!file.exists()) {
            // the one selected doesn't exists
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Editor editor = settings.edit();
        editor.putString(Constants.SELECTED_ROUTE_FILE, routeFilePath);
        editor.commit();

        return routeFilePath;
    }

    /**
     * 
     * @return the route file name
     */
    public static String getRouteFileName() {
        String filePath = getTheRouteFilePath();
        int pos = filePath.lastIndexOf("/");

        if (pos > 0)
            return filePath.substring(pos);

        return null;
    }

    /**
     * 
     * @return
     */
    public static String generateNewFilePath() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/HikingAssistant/";

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }

        GregorianCalendar cal = new GregorianCalendar();

        String fileName = "";
        fileName += cal.get(GregorianCalendar.YEAR);
        fileName += Constants.MONTHS_OF_YEAR[cal.get(GregorianCalendar.MONTH)];
        fileName += cal.get(GregorianCalendar.DAY_OF_MONTH) + "_";
        fileName += cal.get(GregorianCalendar.HOUR_OF_DAY) + "_";
        fileName += cal.get(GregorianCalendar.MINUTE) + ".gpx";

        path += fileName;

        return path;
    }

    /**
     * 
     * @param filePath
     * @param pointsToAdd
     * @return
     */
    public static String addPointsToFile(String filePath, ArrayList<MapPoint> pointsToAdd) {
        if (pointsToAdd == null)
            return null;

        if (filePath == null || filePath.length() == 0) {
            filePath = generateNewFilePath();
        }

        File fileInstance = new File(filePath);

        try {
            if (!fileInstance.exists()) {
                fileInstance.createNewFile();
            }

            XmlSerializer xmlContent = Xml.newSerializer();

            // initialize the os.
            FileOutputStream os = new FileOutputStream(fileInstance);

            xmlContent.setOutput(os, "utf-8");
            xmlContent.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
            xmlContent.startDocument(null, true);
            xmlContent.startTag(null, Constants.XML_TAG_ROOT);
            xmlContent.startTag(null, Constants.XML_TAG_TRKSEG);

            for (MapPoint curPoint : pointsToAdd) {
                // fill xmlContent with the points.
                xmlContent.startTag(null, Constants.XML_TAG_TRACKPTS);
                {
                    xmlContent.attribute(null, Constants.XML_TAG_LATITUDE,
                            Double.toString(curPoint.getLatitude()));
                    xmlContent.attribute(null, Constants.XML_TAG_LONGITUDE,
                            Double.toString(curPoint.getLongitude()));
                    xmlContent.attribute(null, Constants.XML_TAG_TIME,
                            Long.toString(curPoint.getTime()));
                    xmlContent.attribute(null, Constants.XML_TAG_TYPE,
                            Integer.toString(curPoint.getType()));
                    xmlContent.attribute(null, Constants.XML_TAG_NAME,
                            (curPoint.getPointName() != null) ? curPoint.getPointName() : "");

                    xmlContent.startTag(null, Constants.XML_TAG_ALTITUDE);
                    xmlContent.text(Double.toString((curPoint.getAltitude())));
                    xmlContent.endTag(null, Constants.XML_TAG_ALTITUDE);
                }
                xmlContent.endTag(null, Constants.XML_TAG_TRACKPTS);
            }

            xmlContent.endTag(null, Constants.XML_TAG_TRKSEG);
            xmlContent.endTag(null, Constants.XML_TAG_ROOT);
            xmlContent.flush();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
